<?php
namespace App\Service\Xcx\Ywmall;

use App\Service\Xcx\BaseService as Service;

class GorderService extends Service
{
    //商品订单

    //列表
    public static function index($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbYwGorder)->where('del', 0);
        if ($pas['uid']) {
            $db = $db->where('uid', $pas['uid']);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return self::toback(-2, '没有数据', [], $total);
        }
        $ary = [];
        foreach ($res as $v) {
            $ginfo = json_decode($v->ginfo, true);
            $cover = substr($ginfo['cover'], 0, 4)=='http' ? $ginfo['cover'] : env('DOMAIN'). '/' . $ginfo['cover'];
            $codeOne = self::dbConn(self::$dbQr)->where('code', $ginfo['code'])->first();
            $show_code = $codeOne&&$codeOne->show_code ? $codeOne->show_code : '';
            $ary[] = [
                'id' => $v->id, 'title' => $ginfo['gname'],
                'code' => $ginfo['code'], 'show_code' => $show_code,
                'cover' => $cover, 'price' => toNumber($ginfo['price']),
            ];
        }
        return self::toback(0, '', $ary, $total);
    }

    //添加
    public static function add($id, $uid)
    {
        $gOne = self::dbConn(self::$dbYwGorder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($gOne)) {
            return self::toback(-2, '订单不存在');
        }
        $orderno = toCode();
        $ginfo = [
            'id' => $id, 'gname' => $gOne->gname, 'code' => $gOne->code,
            'cover' => $gOne->cover, 'price' => $gOne->price,
        ];
        $up = self::dbConn(self::$dbYwGorder)->insertGetId([
            'uid' => $uid, 'ginfo' => json_encode($ginfo, JSON_UNESCAPED_UNICODE),
            'orderno' => $orderno, 'addtime' => toDate(),
        ]);
        if (!$up) {
            return self::toback(-2, 'error');
        }
        return self::toback();
    }

    //删除
    public static function del($id)
    {
        $gOne = self::dbConn(self::$dbYwGorder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($gOne)) {
            return self::toback(-2, '订单不存在');
        }
        $up = self::dbConn(self::$dbYwGorder)->where('id', $id)->update([
            'del' => 1, 'deltime' => toDate(),
        ]);
        if (!$up) {
            return self::toback(-2, 'error');
        }
        return self::toback();
    }
}